<?php
namespace Home\Controller;
use Think\Controller;
class NoticeController extends Controller {
    /**
     * 微信支付回调通知
     */
    public function wxpay_notify(){
        //接收传送的数据
        $fileContent = file_get_contents("php://input");
        //dump($fileContent);exit;
        $str = '回调'.date('Y-m-d H:i:s');
        file_put_contents('./Org/pay/log.txt',$str."\n",FILE_APPEND);
        if (!$fileContent) {
            exit;
        }
        //转换为simplexml对象
        $xmlResult = simplexml_load_string($fileContent);

        //XML数据的存储
        $newxml = $xmlResult->asXML(); //标准化 XML数据
        $wxarr = $this->FromXml($newxml);

        $orderid = $wxarr['out_trade_no'];
        $return_code = $wxarr['return_code'];
        $return_msg = $wxarr['return_msg'];
        $result_code = $wxarr['result_code'];
        $error_msg = $wxarr['err_code_des'];
        $str = $orderid.'--'.date('Y-m-d H:i').'--'.$return_code.'--'.$return_msg.'--'.$result_code.'--'.$error_msg;
        file_put_contents('./Org/pay/post.txt',$str."\n",FILE_APPEND);


        $key  = 'tzi8APw777UxGOiCc07av87o76XuAp78';  //获取私钥key
        $sign = $this->MakeSign($wxarr, $key);
        //签名验证
        if (!$sign == $wxarr['sign']) {
            $fail = $this->ToXml(array('return_code' => "FAIL", "return_msg" => "签名验证失败"));
            $str = $orderid.'--'.date('Y-m-d H:i').'--'.$fail;
            file_put_contents('./Org/pay/falselog.txt',$str."\n",FILE_APPEND);

            echo $fail;
            exit;
        }

        if ($wxarr['result_code'] == 'SUCCESS' and $wxarr['return_code'] == 'SUCCESS') {
            //更改支付状态
            $timestamp = time()*1000;
            $key = md5($orderid.$timestamp);
            $time = time();
            $url = 'http://schoolgood.cn/Abutment/jxt_updateorder';
            $data = array(
                'timestamp' => $timestamp,
                'order_id' => $orderid,
                'time' => $time,
                'type' => 2,
                'key' => $key
            );
            $res = json_decode(https_curl($url,$data),true);
            if($res['code']==1000 && $res['success']){
                $str = $orderid.'--'.date('Y-m-d H:i').'--upd order type ok';
            }else{
                $str = $orderid.'--'.date('Y-m-d H:i').'--upd order type fail';
            }


            file_put_contents('./Org/pay/truelog.txt',$str."\n",FILE_APPEND);
            echo $this->ToXml(array('return_code' => "SUCCESS", "return_msg" => "OK"));
            exit;
        }
    }

    /**
     * 将xml转为array
     * @param string $xml
     * @throws WxPayException
     */
    public function FromXml($xml) {
        if (!$xml) {
            //throw new WxPayException("xml数据异常！");
            echo json_encode(array('code' => FALSE, 'msg' => "xml数据异常！"));
            exit;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arr;
    }

    /**生成签名
     * @param $arr
     * @param $key
     * @return string
     */
    public function MakeSign($arr, $key) {
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $key;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    public function ToUrlParams($arr) {
        $buff = "";
        foreach ($arr as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    public function ToXml($arr) {
        if (!is_array($arr) || count($arr) <= 0) {
            throw new WxPayException("数组数据异常！");
        }

        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
}